package com.example.demo.filter;

import com.example.demo.entity.Result;
import com.example.demo.util.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class AuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtil jwtUtil;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //如果token合法，否则return;

        if(request.getRequestURL().indexOf("login")>0)
        {
            filterChain.doFilter(request,response);
        }
        String token = request.getHeader("token");
        if(!jwtUtil.validateToken(token))
        {
            Result<String> ret = new Result<>();
            ret.setMsg("token 非法或没有token");
            ret.setCode(401);
            ObjectMapper objectMapper=new ObjectMapper();
            String json = objectMapper.writeValueAsString(ret);
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().println(json);
        }else{
            String username = jwtUtil.getUsernameFromToken(token);
            List<String> roles = jwtUtil.getRolesFromToken(token);
            List<SimpleGrantedAuthority> sga = new ArrayList<SimpleGrantedAuthority>();
            for(String role:roles){
                sga.add(new SimpleGrantedAuthority(role));
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, sga);

            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            filterChain.doFilter(request,response);
        }
    }
}
